package newtank.network.server.handler;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import newtank.data.SyncDataSignal;
import newtank.data.assistant.SyncData;
import server.netty.GpcDataPackage;
import server.netty.NettyGpcRequestHandler;

/**
 * @author lijiahao
 * @since 2022/3/19
 */
public class PositionSyncHandler extends AbstractDataHandler implements EnvironmentHandlerAware {

    private EnvironmentLoadDataHandler environmentLoadDataHandler;

    @Override
    public void handle(ChannelHandlerContext ctx, GpcDataPackage data) {
        if(this.environmentLoadDataHandler == null) {
            setEnvironmentLoadDataHandler(NettyGpcRequestHandler.getEnvironmentLoadDataHandler());
        }
        String unique = data.getUnique();
        String sync = data.getRequestHeader(SyncDataSignal.SYNC_DATA);
        SyncData syncData = JSONObject.parseObject(sync, SyncData.class);
        environmentLoadDataHandler.update(unique, syncData.getPosition(), syncData.getDirection(), syncData.getVersion());
    }

    @Override
    public void setEnvironmentLoadDataHandler(EnvironmentLoadDataHandler environmentLoadDataHandler) {
        this.environmentLoadDataHandler = environmentLoadDataHandler;
    }
}
